package com.netted.operationassistant.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.VolleyError;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.mylhyl.superdialog.SuperDialog;
import com.netted.operationassistant.R;
import com.netted.operationassistant.constant.Constant;
import com.netted.operationassistant.entity.Port;
import com.netted.operationassistant.fragment.MyCodeUtils;
import com.netted.operationassistant.http.HttpRequest;
import com.netted.operationassistant.utils.FaceVerifyUtils;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class Charge2Activity extends BaseActivity {
    private TextView[] tvs;
    private String value = "";

    private TextView secondTv;
    private Handler secondHandler;
    private boolean isStop = false;

    final private Context ctx = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_charge2);
        initView();


    }


    private void initView(){
        tvs = new TextView[6];
        tvs[0] = (TextView)findViewById(R.id.charege_textview1);
        tvs[1] = (TextView)findViewById(R.id.charege_textview2);
        tvs[2] = (TextView)findViewById(R.id.charege_textview3);
        tvs[3] = (TextView)findViewById(R.id.charege_textview4);
        tvs[4] = (TextView)findViewById(R.id.charege_textview5);
        tvs[5] = (TextView)findViewById(R.id.charege_textview6);

        secondTv = (TextView)findViewById(R.id.charege_second);
        String from = getIntent().getStringExtra("from");
        if (null == from || "".equals(from)){
            playSound(ctx,R.raw.s6);
        }
        secondHandler = new Handler();
//        secondThread.start();
        new Thread(secondRunnable).start();
    }


    Runnable secondRunnable = new Runnable() {
        @Override
        public void run() {
            int i = 60;
            while(i >= 0 && !isStop){
                final int second = i;
                secondHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        secondTv.setText(second +"s");
                    }
                });
                i--;
                try{
                    Thread.sleep(1000);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            if (i <= 0){
                exit(null);
            }
        }
    };


    public void del(View view){
        if (value != null && value.length() > 0){
            value = value.substring(0,value.length() - 1);
        }
        showNumber();
    }
    public void clean(View view){
        value = "";
        showNumber();
    }

    public void inputNumber(View view){
        Button b = (Button)view;
        value += b.getText();
        showNumber();
    }



    public void showNumber(){
        if (value != null){

            for(int i = 0; i < 6; i ++){
                if (i < value.length()){
                    tvs[i].setText("●");
                }else{
                    tvs[i].setText("");
                }

            }

            if (value.length() == 6){
                String catbinetId = sharedPreferencesHelper.getSharedPreference("id","") + "";
                if (catbinetId == null || "".equals(catbinetId)){
                    ToastUtils.showLong("丢失系统数据，请联系管理员！");
                }

                final ProgressDialog loadingDialog = ProgressDialog.show(this,"读取中", "正在验证信息", true, false);
                getByToken(catbinetId+"",value,loadingDialog);
                clean(null);
            }
        }
    }

    public void exit(View view){
        Intent intent = new Intent(ctx,MenuActivity.class);
        startActivity(intent);
        this.finish();

    }


    public void qrcode(View view){
        isStop = true;
        Intent intent = new Intent(this,QrCodeActivity.class);
        intent.putExtra("from","Charge2Activity");
        startActivityForResult(intent, MyCodeUtils.RESULT_SUCCESS);
//         this.finish();
    }


    public void openCamera(View view) {
        /*Intent intent = new Intent(this, CameraActivity.class);
        intent.putExtra("from", "Charge2Activity");
        startActivity(intent);
        this.finish();*/

        /*Intent itTrack = new Intent(this, FaceDetectExpActivity.class);
        startActivityForResult(itTrack, 1);*/


        Intent intent = new Intent(this, Camera2Activity.class);
        intent.putExtra("from", "Charge2Activity");
        startActivity(intent);
        this.finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        isStop = false;

        new Thread(secondRunnable).start();
        if (requestCode == CodeUtils.RESULT_SUCCESS) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == MyCodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(MyCodeUtils.RESULT_STRING);
                    String catbinetId = sharedPreferencesHelper.getSharedPreference("id","")+"";
                    if (result.indexOf('[') > -1 && result.indexOf(']') > -1){
                        String deviceId = result.substring(result.indexOf('[') + 1,result.indexOf(']'));
                        final ProgressDialog loadingDialog = ProgressDialog.show(this,"读取中", "正在验证信息", true, false);
                        getByDeviceId(deviceId,catbinetId,loadingDialog);

                    }else if(result.indexOf("admin") > -1){
                        showDialog("提示", "你好，现在准备进入管理员模式，请注意信息保密！", new SuperDialog.OnClickPositiveListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(new Intent(ctx,LoginActivity.class));
                                Charge2Activity.this.finish();
                            }
                        });
                    }

                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == MyCodeUtils.RESULT_FAILED) {
                    Toast.makeText(ctx, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        String from = getIntent().getStringExtra("from");
        if ("CameraActivity".equals(from)){
            getIntent().removeExtra("from");
            final ProgressDialog loadingDialog = ProgressDialog.show(ctx,"验证提示", "正在验证人脸", true, false);
            loadingDialog.show();
            final String groupId = getIntent().getStringExtra("groupId");

            final String base64 = getIntent().getStringExtra("base64");

            new Thread(new Runnable() {
                @Override
                public void run() {

                    String returnStr = FaceVerifyUtils.search(groupId,base64);
                    loadingDialog.dismiss();
                    JSONObject returnJson = JSONObject.parseObject(returnStr);
                    Integer faceCode = returnJson.getInteger("error_code");
                    if (faceCode == 0){
                        JSONObject resultJson = returnJson.getJSONObject("result");
                        if (resultJson != null){
                            JSONArray userList = resultJson.getJSONArray("user_list");
                            if (userList != null && userList.size() > 0){
                                JSONObject userJson = userList.getJSONObject(0);

                                LogUtils.e("face userJson###################"+userJson);
                                String catbinetId = sharedPreferencesHelper.getSharedPreference(Constant.XML_CATBINET_ID, "") + "";
                                String studentId = userJson.getString("user_id");
                                Float score = userJson.getFloatValue("score");
                                if (score < 85){
                                    showDialog("提示", "人脸识别不匹配", null);
                                }else{
                                    getByStudentId(catbinetId,studentId,loadingDialog);
                                }


                            }

                        }
                    }else{
                        if (loadingDialog != null && loadingDialog.isShowing()){
                            loadingDialog.dismiss();
                        }
                        String tips = Constant.getFaceCode().get(faceCode);
                        if (StringUtils.isEmpty(tips)){
                            tips = "人脸识别错误";
                        }
                        showDialog("提示", tips, new SuperDialog.OnClickPositiveListener() {
                            @Override
                            public void onClick(View v) {
//                                startActivity(new Intent(GetDevice2Activity.this,MenuActivity.class));
//                                GetDevice2Activity.this.finish();
                            }
                        });
                    }

                }
            }).start();

        }else if (null == from || "".equals(from)){
//            playSound(ctx,R.raw.s6);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopSound();
        isStop = true;
    }

    public void getByDeviceId(String deviceId, String catbinetId, final ProgressDialog loadingDialog){


        Map<String,String > params = new HashMap<>();
        params.put("catbinetId",catbinetId+"");
        params.put("deviceId", deviceId);
        params.put("action", "二维码充电");

        String url = Constant.HOST + "/ws/opt/getByDeviceId";
        request.post(url, params, "post", new HttpRequest.Callback() {
            @Override
            public void onSuccess(String response) {
                loadingDialog.dismiss();
                try {
                    if (StringUtils.isEmpty(response)){
                        showDialog("提示","返回数据异常",null);
                        return;
                    }else{
                        JSONObject resJson = JSONObject.parseObject(response);
                        if ("success".equals(resJson.getString("flag"))){
                            String data = resJson.getString("data");
                            if(!StringUtils.isEmpty(data)){
                                JSONObject dataJson = JSONObject.parseObject(data);
                                String studentName = dataJson.getString("studentName");
                                String overTime = dataJson.getString("overTime");
                                String port = dataJson.getString("port");
                                Port p = getPortStatus(port);
                                if (p == null || p.getIsHas().equals("Y")){
                                    showDialog("提示", "仓内已有平板,不可再次放入充电", null);
                                    return;
                                }
                                openPort(port);
                                Thread.sleep(1000);
                                serialValue = "";
                                String text = "你好，"+studentName+"同学，仓门已打开，请放入平板后关闭仓门，使用日期到："+
                                        overTime+"，祝你使用愉快！";
                                Date overDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(overTime);
                                if (overDate.getTime()<System.currentTimeMillis()){
                                    text = "你好，"+studentName+"同学，仓门已打开，请放入平板后关闭仓门，使用日期到："+
                                            overTime+"，您的平板已经超出使用时间，请及时充值或归还平板！";
                                }
                                showDialog("提示", text, new SuperDialog.OnClickPositiveListener() {
                                    @Override
                                    public void onClick(View v) {
                                        startActivity(new Intent(ctx,MenuActivity.class));
                                        Charge2Activity.this.finish();
                                    }
                                });
                                playSound(ctx,R.raw.s1);
                                return;
                            }else{
                                showDialog("提示","返回数据异常",null);
                                return;
                            }
                        }else{
                            if ("错误的取机码".equals(resJson.getString("message"))){
                                playSound(ctx,R.raw.s7);
                            }
                            showDialog("提示",resJson.getString("message"),null);
                            return;
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    LogUtils.e(e.getMessage());
                    showDialog("提示","获取数据异常",null);
                }


            }

            @Override
            public void onError(VolleyError error) {
                loadingDialog.dismiss();
                showDialog("错误提示",error.toString(),null);
            }
        });
    }

    public void getByToken(String catbinetId,String token,final ProgressDialog loadingDialog){


        Map<String,String > params = new HashMap<>();
        params.put("catbinetId",catbinetId+"");
        params.put("token", token);
        params.put("action", "号码充电");

        String url = Constant.HOST + "/ws/opt/getByToken";
        request.post(url, params, "post", new HttpRequest.Callback() {
            @Override
            public void onSuccess(String response) {
                loadingDialog.dismiss();
                try {
                    if (StringUtils.isEmpty(response)){
                        showDialog("提示","返回数据异常",null);
                        return;
                    }else{
                        JSONObject resJson = JSONObject.parseObject(response);
                        if ("success".equals(resJson.getString("flag"))){
                            String data = resJson.getString("data");
                            if(!StringUtils.isEmpty(data)){
                                JSONObject dataJson = JSONObject.parseObject(data);
                                String studentName = dataJson.getString("studentName");
                                String overTime = dataJson.getString("overTime");
                                String port = dataJson.getString("port");
                                Port p = getPortStatus(port);
                                if (p == null || p.getIsHas().equals("Y")){
                                    showDialog("提示", "仓内已有平板,不可再次放入充电", null);
                                    return;
                                }
                                openPort(port);
                                Thread.sleep(1000);
                                serialValue = "";
                                String text = "你好，"+studentName+"同学，仓门已打开，请放入平板后关闭仓门，使用日期到："+
                                        overTime+"，祝你使用愉快！";
                                Date overDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(overTime);
                                if (overDate.getTime()<System.currentTimeMillis()){
                                    text = "你好，"+studentName+"同学，仓门已打开，请放入平板后关闭仓门，使用日期到："+
                                            overTime+"，您的平板已经超出使用时间，请及时充值或归还平板！";
                                }
                                showDialog("提示", text, new SuperDialog.OnClickPositiveListener() {
                                    @Override
                                    public void onClick(View v) {
                                        startActivity(new Intent(ctx,MenuActivity.class));
                                        Charge2Activity.this.finish();
                                    }
                                });
                                playSound(ctx,R.raw.s1);
                                return;
                            }else{
                                showDialog("提示","返回数据异常",null);
                                return;
                            }
                        }else{
                            if ("错误的取机码".equals(resJson.getString("message"))){
                                playSound(ctx,R.raw.s7);
                            }
                            showDialog("提示",resJson.getString("message"),null);
                            return;
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    LogUtils.e(e.getMessage());
                    showDialog("提示","获取数据异常",null);
                }


            }

            @Override
            public void onError(VolleyError error) {
                loadingDialog.dismiss();
                showDialog("错误提示",error.toString(),null);
            }
        });
    }


    public void getByStudentId(String catbinetId,String studentId,final ProgressDialog loadingDialog){


        Map<String,String > params = new HashMap<>();
        params.put("catbinetId",catbinetId+"");
        params.put("studentId", studentId);
        params.put("action", "人脸识别充电");

        String url = Constant.HOST + "/ws/opt/getByStudentId";
        request.post(url, params, "post", new HttpRequest.Callback() {
            @Override
            public void onSuccess(String response) {
                loadingDialog.dismiss();
                try {
                    if (StringUtils.isEmpty(response)){
                        showDialog("提示","返回数据异常",null);
                        return;
                    }else{
                        JSONObject resJson = JSONObject.parseObject(response);
                        if ("success".equals(resJson.getString("flag"))){
                            String data = resJson.getString("data");
                            if(!StringUtils.isEmpty(data)){
                                JSONObject dataJson = JSONObject.parseObject(data);
                                String studentName = dataJson.getString("studentName");
                                String overTime = dataJson.getString("overTime");
                                String port = dataJson.getString("port");
                                Port p = getPortStatus(port);
                                if (p == null || p.getIsHas().equals("Y")){
                                    showDialog("提示", "仓内已有平板,不可再次放入充电", null);
                                    return;
                                }
                                openPort(port);
                                Thread.sleep(1000);
                                serialValue = "";
                                String text = "你好，"+studentName+"同学，仓门已打开，请放入平板后关闭仓门，使用日期到："+
                                        overTime+"，祝你使用愉快！";
                                Date overDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(overTime);
                                if (overDate.getTime()<System.currentTimeMillis()){
                                    text = "你好，"+studentName+"同学，仓门已打开，请放入平板后关闭仓门，使用日期到："+
                                            overTime+"，平板已经超出使用时间，请及时充值或归还平板！";
                                }
                                showDialog("提示", text, new SuperDialog.OnClickPositiveListener() {
                                    @Override
                                    public void onClick(View v) {
                                        startActivity(new Intent(ctx,MenuActivity.class));
                                        Charge2Activity.this.finish();
                                    }
                                });
                                playSound(ctx,R.raw.s1);
                                return;
                            }else{
                                showDialog("提示","返回数据异常",null);
                                return;
                            }
                        }else{
                            if ("错误的取机码".equals(resJson.getString("message"))){
                                playSound(ctx,R.raw.s7);
                            }
                            showDialog("提示",resJson.getString("message"),null);
                            return;
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    LogUtils.e(e.getMessage());
                    showDialog("提示","获取数据异常",null);
                }


            }

            @Override
            public void onError(VolleyError error) {
                loadingDialog.dismiss();
                showDialog("错误提示",error.toString(),null);
            }
        });
    }
}
